package com.six.library.utils

import com.six.library.model.ResultData
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.web.client.RestTemplate


/*-*- coding:utf-8 -*-
 * @Author  : debi
 * @Time    : 10/25/22
 * @Software: IntelliJ IDEA
 */
class RestTemplateUtils(val restTemplate: RestTemplate) {
    //    Constant.Flower + "/api/selectAll",
    inline fun <reified T> getForObject(front: String, route: String): T? {
        return restTemplate.getForObject<T>(
            front + route,
            T::class.java
        ) as T
    }

    /*傳遞數據*/
    fun setPostData(front: String, route: String, entity: HttpEntity<ResultData>): ResultData? {
        return restTemplate.postForEntity<ResultData>(
            front + route,
            entity,
            ResultData::class.java
        ).body
    }

    /**
     * Set result data
     *     * 传递json数据
     * @param T 返回类型
     * @param V 传递数据
     * @param front
     * @param route
     * @param data
     * @return
     */
    inline fun <reified T, V> setPostData(front: String, route: String, data: V): T? {
        return restTemplate.postForEntity(
            front + route,
            HttpEntity<V>(data, HttpHeaders().apply {
                this.contentType = MediaType.parseMediaType("application/json;charset=UTF-8")
            }),
            T::class.java
        ).body
    }
    inline fun <reified T> setPostDataAny(front: String, route: String, bodyData: Any): T? {
        return restTemplate.postForEntity(
            front + route,
            HttpEntity<Any>(bodyData, HttpHeaders().apply {
                this.contentType = MediaType.APPLICATION_JSON
            }),
            T::class.java
        ).body
    }

    companion object
}
